package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties wechatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    public Result<UserLoginVO> login(UserLoginDTO userLoginDTO) {
        //调用微信小程序接口，换取用户的openid
       String openid = getOpenid(userLoginDTO.getCode());
       //根据openid查询用户信息，判断用户是否为新用户，如果是新用户就自动完成注册
       User user = userMapper.selectByOpenid(openid);
       if(user == null){
           //新用户，自动完成注册
           User user1 = new User();// 用户信息
           user1.setOpenid(openid);// 用户唯一标识
           user1.setCreateTime(LocalDateTime.now());// 创建时间
           userMapper.sever(user1);
       }
       //如果是老用户，直接登录成功
        Map<String, Object> claims = new HashMap<>();// jwt令牌中存放用户的信息
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //查询商家信息
        Merchant merchant = merchantMapper.selectById(1l);

        //配送费计算
        String shopLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(shopLocation, userLoginDTO.getLocation());
        //构建返回值
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openid)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(merchant.getId())
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(delivoryCost)
                .build();
        return Result.success(userLoginVO);

    }

    private String getOpenid(String code) {
        Map<String, String> map = new HashMap<>();// 请求参数
        map.put("appid", wechatProperties.getAppid());// 小程序的id
        map.put("secret", wechatProperties.getSecret());// 小程序的密钥
        map.put("js_code", code);// 小程序调用wx.login返回的code
        map.put("grant_type", "authorization_code");// 固定参数
        String jsonStr = HttpClientUtil.doGet(WX_LOGIN_URL, map);// 调用微信接口
        Map res = JSON.parseObject(jsonStr, Map.class);// 将返回的json字符串转换为map
        return  res.get("openid").toString();// 返回openid
    }
}
